import os

import pandas as pd
from pandas import Series

from src2.BaseThread import BaseThread
from src2.FrameParser import FrameParser


class OomMonitor(BaseThread):
    def __init__(self, dir):
        BaseThread.__init__(self, "OomMonitor", 1)
        self.file_index = 0
        self.frame_parser = FrameParser()
        self.dir_path = dir
        self.files = []
        self.oom_series: Series = pd.Series(name='LowMemoryKiller')
        self.temp = None

    def pre_job(self):
        self.files = os.listdir(self.dir_path)
        self.files.sort(key=lambda x: int(x[:-4]))

    def after_job(self):
        pass

    def real_job(self):
        if self.file_index >= len(self.files):
            return False

        self.print(str(self.file_index) + '/' + str(len(self.files) - 1) + '  ' + self.files[self.file_index])

        file = self.dir_path + "/" + self.files[self.file_index]
        self.file_index += 1

        with open(file, 'r') as f:
            lines = f.readlines()
            for line in lines:
                if len(line) > 0:
                    self.parse_line(line[:-1])
                elif line == '':
                    break

        return True

    def run_until_finish(self):
        self.start()
        self.thread.join()

    def parse_line(self, line):
        elements = line.split()

        if len(elements) != 11:
            return

        if elements[5][:-1] == 'lowmemorykiller' and self.temp == None:
            self.temp = {}
        elif elements[6] == 'Total' and elements[7] == 'free':
            self.temp['free'] = elements[10][:-2]
            return
        elif elements[6] == 'Total' and elements[7] == 'file':
            if self.temp['timestamp'] not in self.oom_series.index.tolist():
                self.oom_series = self.oom_series.append(
                    pd.Series(data=[self.temp['free']], index=[self.temp['timestamp']]))
            self.temp = None
            return

        times = elements[1].split(':')
        hh = times[0]
        mm = times[1]
        ss = times[2].split('.')[0]

        times = elements[0].split('-')
        YY = '70'
        MM = times[0]
        DD = times[1]

        timestamp = YY + MM + DD + hh + mm + ss
        self.temp['timestamp'] = timestamp
        self.temp['process_name'] = elements[7]

    def get_info(self):
        self.oom_series.name = 'LowMemoryKiller'
        return self.oom_series
